package com.example.recipes;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author Creared by wangyang on 2019-01-29 15:04
 * email:techyang.wangy.@ymm56.com
 */
public class DistributedLock {
    private static CuratorFramework client = CuratorFrameworkHolder.CURATOR_FRAMEWORK;

    private static final String ZK_BOOK_DISTRIBUTE_LOCK = "/zk-book/distributeLock";

    public static void main(String[] args) {
        client.start();
        InterProcessLock ipl = new InterProcessMutex(client,ZK_BOOK_DISTRIBUTE_LOCK);
        CountDownLatch cdl = new CountDownLatch(1);

        for (int i = 0; i < 30; i++) {
            new Thread(() ->{
                try {
                    cdl.await();
                    ipl.acquire();
                    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss|SSS");
                    String orderNo = sdf.format(new Date());
                    System.out.println("生成的订单号：" + orderNo);
                } catch (Exception ignore) {
                } finally {
                    try {
                        ipl.release();
                    } catch (Exception ignore) {
                    }
                }

            }).start();
        }

        cdl.countDown();
    }
}
